public class Test {

    public static void getNext(String sub,int[] next){
        next[0] = -1;
        next[1] = 0;
        int k = 0;
        int lenSub = sub.length();
        int i = 2;
        while(i < lenSub){
            if(k == -1 || sub.charAt(i-1) == sub.charAt(k)){
                k++;
                i++;
            }else{
                k = next[k];
            }
        }
    }

    /**
     * @param str 主串
     * @param sub 字串
     * @param pos 从主串pos位置开始找
     * @return 返回与字串相匹配的主串第一个位置下标
     */
    public static int KMP(String str, String sub, int pos) {
        if (str == null || sub == null) return -1;
        int lenStr = str.length();
        int lenSub = sub.length();
        if (lenStr == 0 || lenSub == 0) return -1;
        if (pos >= lenStr) return -1;

        int i = pos; //i 用来遍历主串
        int j = 0;   //j 用来遍历字串

        int[] next = new int[lenSub];
        getNext(sub,next);

        while (i < lenStr && j < lenSub) {
            if (j == -1 || str.charAt(i) == sub.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }
        if (j >= lenSub) {
            return i - j;
        }
        return -1;

    }

    public static void main(String[] args) {
        System.out.println(KMP("abababcdddd", "abcd", 0));
        System.out.println(KMP("abababcdddd", "dd", 0));
    }
}
